import { Op } from "sequelize"
import { Blog } from "../model/Blog.js"
const fn_list = async (ctx, next) => {
    let keyword = ctx.request.query.keyword || '';
    let where
    if (keyword) {
        where = {
            [Op.or]: [{
                title: {
                    [Op.like]: `%${keyword}%`
                },

            },
            {
                author: {
                    [Op.like]: `%${keyword}%`
                },
            },
            ]
        }
    }
    let blogs = await Blog.findAll({ where });
    ctx.body = {
        code: 1000,
        msg: 'ok',
        data: blogs
    }


}
const fn_getById = async (ctx, next) => {
    let id = ctx.params.id || 0
    let blog = await Blog.findByPk(id)
    console.log(blog)
    ctx.body = {
        code: 1000,
        msg: '获取ok',
        data: blog
    }


    // ctx.body='id获取'
}
const fn_add = async (ctx, next) => {
    let obj = ctx.request.body;
    console.log(obj)
    let count = await Blog.create(obj)
    ctx.body = {
        code: 1000,
        msg: '新增ok',
        data: count
    }


    // ctx.body='新增'
}
const fn_del = async (ctx, next) => {
   
    let id = ctx.params.id || 0
    
   let count=  await Blog.destroy({
        where: {
            id: id
        }
    })
    let res
    if (count === 1) {
        res = {
            code: 1000,
            msg: '欧内的手',
            data: null
        }
    } else {
        res = {
            code: 4000,
            msg: '好汉',
            data: null
        }
    }
    ctx.body = res
}
const fn_edit = async (ctx, next) => {

    let id = ctx.params.id || 0
    let obj = ctx.request.body
    await Blog.update(obj, {
        where: {
            id: id
        }
    })
    ctx.body = {
        code: 1000,
        msg: "修改ok",
        data: null
    }
}
export default [
    {
        method: 'get',
        url: '/blogs',
        fn: fn_list
    },
    {
        method: 'get',
        url: '/blogs/:id',
        fn: fn_getById
    },
    {
        method: 'post',
        url: '/blogs',
        fn: fn_add
    },
    {
        method: 'put',
        url: '/blogs/:id',
        fn: fn_edit
    },
    {
        method: 'del',
        url: '/blogs/:id',
        fn: fn_del
    }


]